<?php
function loadCache($cache_names, $force = false)
{
	global $_FANWE;
	static $loaded_cache = array();
	$cache_names = is_array($cache_names) ? $cache_names : array($cache_names);
	$caches = array();
	foreach ($cache_names as $k)
	{
		if(!isset($loaded_cache[$k]) || $force)
		{
			$caches[] = $k;
			$loaded_cache[$k] = true;
		}
	}

	if(!empty($caches))
	{
		$cache_data = cacheData($caches);
		foreach($cache_data as $cname => $data)
		{
			if($cname == 'setting')
			{
				$_FANWE['setting'] = $data;
			}
			else
			{
				$_FANWE['cache'][$cname] = $data;
			}
		}
	}
	return true;
}

function cacheData($cache_names)
{
	global $_FANWE;
	static $isfile_cache, $allow_memory;

	if($isfile_cache === NULL)
	{
		//$isfile_cache = $_FANWE['config']['cache']['type'] == 'file';
		$isfile_cache = true;
		$allow_memory = memoryHandler('check');
	}

	$data = array();
	$cache_names = is_array($cache_names) ? $cache_names : array($cache_names);
	if($allow_memory)
	{
		$new_array = array();
		foreach ($cache_names as $name)
		{
			$data[$name] = memoryHandler('get', $name);
			if($data[$name] === NULL)
			{
				$data[$name] = NULL;
				$new_array[] = $name;
			}
		}
		if(empty($new_array))
		{
			return $data;
		}
		else
		{
			$cache_names = $new_array;
		}
	}

	if($isfile_cache)
	{
		$lost_caches = array();
		foreach($cache_names as $cache_name)
		{
			if(!@include_once(FANWE_ROOT.'./public/caches/'.$cache_name.'.cache.php'))
			{
				$lost_caches[] = $cache_name;
			}
		}

		if(!$lost_caches)
		{
			return $data;
		}

		$cache_names = $lost_caches;

		unset($lost_caches);
	}

	//$query = DB::query("SELECT /*!40001 SQL_CACHE */ * FROM ".DB::table('caches')." WHERE ckey IN ('".implode("','", $cache_names)."')");

	/*while($sys_cache = DB::fetch($query))
	{
		print_r($sys_cache['cval']);
			exit;
		$data[$sys_cache['ckey']] = $sys_cache['ctype'] ? unserialize($sys_cache['cval']) : $sys_cache['cval'];
		$allow_memory && (memoryHandler('set', $sys_cache['ckey'], $data[$sys_cache['ckey']]));
		if($isfile_cache)
		{
			$cache_data = '$data[\''.$sys_cache['ckey'].'\'] = '.var_export($data[$sys_cache['ckey']], true).";\n\n";
			if($fp = @fopen(FANWE_ROOT.'./public/caches/'.$sys_cache['ckey'].'.cache.php', 'wb'))
			{
				fwrite($fp, "<?php\n$cache_data?>");
				fclose($fp);
			}

		}
	}*/

	foreach($cache_names as $name)
	{
		if($data[$name] === NULL)
		{
			$data[$name] = NULL;
			$allow_memory && (memoryHandler('set', $name, array()));
		}
	}

	return $data;
}

function saveCache($cache_name, $data)
{
	global $_FANWE;
	static $isfile_cache = NULL, $allow_memory = NULL;
	if($isfile_cache === NULL)
	{
		//$isfile_cache = $_FANWE['config']['cache']['type'] == 'file';
		$isfile_cache = true;
		$allow_memory = memoryHandler('check');
	}

	$allow_memory && memoryHandler('rm', $cache_name);
	$allow_memory && (memoryHandler('set', $cache_name, $data));
	if($isfile_cache)
	{
		$cache_data = '$data[\''.$cache_name.'\'] = '.var_export($data, true).";\n\n";
		if($fp = @fopen(FANWE_ROOT.'./public/caches/'.$cache_name.'.cache.php', 'w'))
		{
			fwrite($fp, "<?php\n$cache_data?>");
			fclose($fp);
		}
	}
}

function updateCache($cache_names = '')
{
	$update_list = empty($cache_names) ? array() : (is_array($cache_names) ? $cache_names : array($cache_names));

	if(!$update_list)
	{
		@require_once import('cache/setting');
		bindCacheSetting();
		$cache_dir = FANWE_ROOT.'./core/cache';
		$cache_dir_handle = dir($cache_dir);
		while($entry = $cache_dir_handle->read())
		{
			if(!in_array($entry, array('.', '..')) && preg_match("/^([\w]+)\.cache\.php$/", $entry, $entryr) && $entryr[1] != 'setting' && substr($entry, -10) == '.cache.php' && is_file($cache_dir.'/'.$entry))
			{
				require_once import('cache/'.$entryr[1]);
				call_user_func('bindCache'.ucfirst($entryr[1]));
			}
		}
	}
	else
	{
		foreach($update_list as $entry)
		{
			require_once import('cache/'.$entry);
			call_user_func('bindCache'.ucfirst($entry));
		}
	}

}

function writeCache($script, $cache_data, $sufix = '.cache')
{
	$dir = FANWE_ROOT.'./public/caches/';
	if(!is_dir($dir))
	{
		@mkdir($dir, 0777);
	}
	if($fp = @fopen("$dir$script$sufix.php", 'wb'))
	{
		fwrite($fp, "<?php\n$cache_data?>");
		fclose($fp);
	}
	else
	{
		exit('Can not write to cache files, please check directory ./public/ and ./public/caches/ .');
	}
}

function memoryHandler($cmd, $key='', $value='', $ttl = 0)
{
	$fanwe = & FanweService::instance();
	if($cmd == 'check')
	{
		return  $fanwe->memory->enable ? $fanwe->memory->type : '';
	}
	elseif($fanwe->memory->enable && in_array($cmd, array('set', 'get', 'rm')))
	{
		switch ($cmd)
		{
			case 'set': return $fanwe->memory->set($key, $value, $ttl); break;
			case 'get': return $fanwe->memory->get($key); break;
			case 'rm': return $fanwe->memory->rm($key); break;
		}
	}
	return NULL;
}
?>